package com.mingzhi.lotterysystem.service.activitystatus.operator;

import com.mingzhi.lotterysystem.dao.dataobject.ActivityDO;
import com.mingzhi.lotterysystem.dao.mapper.ActivityMapper;
import com.mingzhi.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.mingzhi.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.mingzhi.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.mingzhi.lotterysystem.service.enums.ActivityStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ActivityOperator:活动操作符
 */
@Component
public class ActivityOperator extends AbstractActivityOperator {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //要判断奖品是否抽完了
        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetActivityStatus = convertActivityStatusDTO.getTargetActivityStatus();
        if (null == activityId || null == targetActivityStatus) {
            return false;
        }
        ActivityDO activityDO = activityMapper.selectActivityId(activityId);
        if (null == activityDO) {
            return false;
        }
        //如果状态一致，就不处理
        if (targetActivityStatus.name().equals(activityDO.getStatus())) {
            return false;
        }
        //奖品是否抽完
        //查询 init 状态下奖品的个数
        int countPrize = activityPrizeMapper.countPrize(activityId, ActivityPrizeStatusEnum.INIT.name());
        if (countPrize > 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            activityMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getTargetActivityStatus().name());
            return true;
        }catch (Exception e){
            return false;
        }
    }

}
